#!/usr/bin/env bash
CUR_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=../shell_config.sh
. "$CUR_DIR"/../shell_config.sh

CLICKHOUSE_USER="user_$CLICKHOUSE_DATABASE"

$CLICKHOUSE_CLIENT "

DROP USER IF EXISTS ${CLICKHOUSE_USER};
CREATE USER ${CLICKHOUSE_USER};

CREATE TABLE ${CLICKHOUSE_DATABASE}.02703_rqtable (x UInt8) ENGINE = MergeTree ORDER BY x;
INSERT INTO ${CLICKHOUSE_DATABASE}.02703_rqtable VALUES (1), (2), (3), (4);

SELECT '-- row policies for database';
CREATE ROW POLICY ${CLICKHOUSE_DATABASE}_db_policy ON ${CLICKHOUSE_DATABASE}.* USING 1 AS PERMISSIVE TO ALL;
CREATE ROW POLICY ${CLICKHOUSE_DATABASE}_tb_policy ON ${CLICKHOUSE_DATABASE}.table USING 1 AS PERMISSIVE TO ALL;
SELECT '  -- SHOW CREATE POLICY ${CLICKHOUSE_DATABASE} ON ${CLICKHOUSE_DATABASE}.*';
SHOW CREATE POLICY ${CLICKHOUSE_DATABASE}_db_policy ON ${CLICKHOUSE_DATABASE}.*;
SELECT '  -- SHOW CREATE POLICY ON ${CLICKHOUSE_DATABASE}.*';
SHOW CREATE POLICY ON ${CLICKHOUSE_DATABASE}.*;
SELECT '  -- SHOW CREATE POLICY ON ${CLICKHOUSE_DATABASE}.\`*\`';
SHOW CREATE POLICY ON ${CLICKHOUSE_DATABASE}.\`*\`;
DROP POLICY ${CLICKHOUSE_DATABASE}_db_policy ON ${CLICKHOUSE_DATABASE}.*;
DROP POLICY ${CLICKHOUSE_DATABASE}_tb_policy ON ${CLICKHOUSE_DATABASE}.table;
"

$CLICKHOUSE_CLIENT --query "CREATE ROW POLICY any_02703 ON *.some_table USING 1 AS PERMISSIVE TO ALL;" 2>&1 | grep -q "SYNTAX_ERROR"

$CLICKHOUSE_CLIENT "
CREATE TABLE 02703_rqtable_default (x UInt8) ENGINE = MergeTree ORDER BY x;

CREATE ROW POLICY ${CLICKHOUSE_DATABASE}_filter_11_db_policy ON * USING x=1 AS permissive TO ALL;
CREATE ROW POLICY ${CLICKHOUSE_DATABASE}_filter_11_policy ON 02703_rqtable_default USING x=2 AS permissive TO ALL;

INSERT INTO 02703_rqtable_default VALUES (1), (2), (3), (4);

SELECT 'R1, R2: (x == 1) OR (x == 2)';
SELECT * FROM 02703_rqtable_default;

DROP TABLE 02703_rqtable_default;

SELECT 'Check system.query_log';
SYSTEM FLUSH LOGS query_log;
SELECT query, used_row_policies FROM system.query_log WHERE current_database == currentDatabase() AND type == 'QueryStart' AND query_kind == 'Select' ORDER BY event_time_microseconds;

DROP ROW POLICY ${CLICKHOUSE_DATABASE}_filter_11_db_policy ON *;
DROP ROW POLICY ${CLICKHOUSE_DATABASE}_filter_11_policy ON 02703_rqtable_default;

USE ${CLICKHOUSE_DATABASE};
SELECT '  -- CREATE DATABASE-LEVEL POLICY IN CURRENT DATABASE';
CREATE ROW POLICY db2_02703 ON * TO ${CLICKHOUSE_USER};
SHOW CREATE POLICY db2_02703 ON *;

DROP ROW POLICY db2_02703 ON *;

DROP USER ${CLICKHOUSE_USER};
"
